#!/bin/bash

_ocops_completions()
{
	local result
	local n=${#COMP_WORDS[@]}
	n=$((n-1))

	local cmd=(ocos ops "${COMP_WORDS[@]}")
	cmd[2]="--bashcomp"
	unset cmd[$((n+3))]
	result="$(${cmd[@]} </dev/null 2>/dev/null)"
	local lead="${result%% *}"
	if [ -z "${lead##*:*}" -o -z "${result##*$'\n' *}" -o -z "${result##*$'\t'*}" ]; then
		result=
	fi
	
	if [ -n ".$result" ]; then
		local IFS=$'\n'
		local sug=($(compgen -W "$result" -- ${COMP_WORDS[$n]}))
		if [ "${#sug[@]}" == "1" ]; then
			local number="${sug[0]/%\ */}"
			COMPREPLY=("$number")
		else
			for i in "${!sug[@]}"; do
				sug[$i]="$(printf '%*s' "-$COLUMNS"  "${sug[$i]}")"
			done

			COMPREPLY=("${sug[@]}")
		fi
	fi
}
complete -F _ocops_completions oc-ops
